package main

import (
	"fmt"
	"webstack/config"
	"webstack/controller"
	"webstack/crons"
	"webstack/middleware"

	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	"github.com/robfig/cron/v3"
)

func main() {
	go jcron()

	gin.DisableConsoleColor()
	if config.Debug {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(cors.Default())
	r.Use(static.Serve("/", static.LocalFile(config.FrontPath, false)))
	r.Static("/backstage", config.ManagerPath)

	api := r.Group("/api")
	auth := api.Group("")
	auth.Use(middleware.CheckToken)

	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	api.POST("/login", controller.AdminLogin)
	// 搜索引擎分类
	auth.POST("/search-engines-category/add", controller.AddSearchEnginesCategory)
	auth.POST("/search-engines-category/delete", controller.DeleteSearchEnginesCategory)
	auth.POST("/search-engines-category/update", controller.UpdateSearchEnginesCategory)
	auth.GET("/search-engines-category/get", controller.GetSearchEnginesCategory)
	// 搜索引擎
	auth.POST("/search-engines/add", controller.AddSearchEngines)
	auth.POST("/search-engines/delete", controller.DeleteSearchEngines)
	auth.POST("/search-engines/update", controller.UpdateSearchEngines)
	// 网址分类
	auth.POST("/web-category/add", controller.AddWebCategory)
	auth.POST("/web-category/delete", controller.DeleteWebCategory)
	auth.POST("/web-category/update", controller.UpdateWebCategory)
	auth.GET("/web-category/get", controller.GetWebCategory)
	auth.GET("/web-category/get-all", controller.GetAllWebCategories)
	auth.POST("/web-category/set-order", controller.SetWebCategoryOrd)
	auth.GET("/web-category/get-sub", controller.GetSubsWebCategory)
	// 网址
	auth.POST("/web/add", controller.AddWeb)
	auth.POST("/web/delete", controller.DeleteWeb)
	auth.POST("/web/update", controller.UpdateWeb)
	auth.GET("/web/get-un-category", controller.GetUnCategoryWeb) // 获取未分类的网址
	auth.POST("/web/set-multi-category", controller.SetMultiCategory)

	// 前端
	api.GET("/search-engines", controller.GetSearchEnginesCategory)
	api.GET("/web", middleware.SetToken, controller.GetWebCategory)
	api.GET("/web/sub", middleware.SetToken, controller.GetSubsWebCategory)
	api.GET("/web/all", controller.GetAllWebCategoryData)

	fmt.Println("Listening on port " + config.ServerPort)
	r.Run(config.ServerPort)
}

func jcron() {
	println("start jcron")

	job := cron.New(cron.WithSeconds())
	job.AddFunc("@every 1h", crons.FetchTitle)
	job.Start()
}
